//
//  JKSkinningTool.swift
//  JKSwiftSkinning
//
//  Created by 王冲 on 2019/1/28.
//  Copyright © 2019年 JK科技有限公司. All rights reserved.
//

import UIKit

let JKTheme = "theme"

// OC 枚举, 整型
// swift ,枚举, 是任意类型
// 图片的名字
enum JKThemeType: String {
    case Zhongqiu = "skin/zhongqiu/"
    case Guoqing = "skin/guoqing/"
    case Chunjie = "skin/chunjie/"
    case None = "none"
}

// 图片的类型
enum JKSkinImageType: String {
    case SkinBack = "back.png"
    case SkinIcon = "icon"
}

// 换肤的颜色
enum JKSkinColorType: String {
    case SkinLabelColor = "SkinLabelColor"
}

class JKSkinningTool: NSObject {

    // 工具类内部存在的问题
    // "theme" : 是一个字符串, 既然是字符串, 就有可能写错
    // 主题提供, 没有明确指示, 外界直接传递一个字符串过来
    
    
    // MARK: - 保存换肤值
    class func saveSkinning(imageName:JKThemeType) {
        
        UserDefaults.standard.set(imageName.rawValue, forKey: JKTheme)
        UserDefaults.standard.synchronize()
    }
    
    // MARK: - 获取换肤值(图片的名字)
    class func getSkinning() -> JKThemeType?{
        
        guard let theme = UserDefaults.standard.value(forKey: JKTheme) else {
            return .None
        }
        
        let name = theme as! String
        return JKThemeType(rawValue: name)
    }
    
    // MARK：获取图片
    class func getSkinImage(type:JKSkinImageType) -> UIImage? {

        guard let theme = JKSkinningTool.getSkinning() else {
            return nil
        }
        
        let imageName = theme.rawValue
        
        return UIImage.init(named: "JKSkinningTool.bundle/"+imageName+type.rawValue)
        
    }
    
    // MARK: 当前肤色下颜色的获取
    class func getSkinColor(type:JKSkinColorType) -> UIColor? {
        
        // 1. 获取当前主题
        guard let theme = JKSkinningTool.getSkinning() else {
            return nil
        }
        let imageName = theme.rawValue
        // 2.颜色的存储方案: r255 g 222,b 123,plst文件字典数组里面
        // 2.1 取出不同主题对应路径下面的颜色配置文件
        let colorPath = Bundle.main.path(forResource: "JKSkinColorConfig.plist", ofType: nil, inDirectory: "JKSkinningTool.bundle/"+imageName)
        // 3. 加载里面所有的颜色(字典 key, 数组)
        let colorDict = NSDictionary(contentsOfFile: colorPath!) ?? NSDictionary()
        
        // 4. 根据颜色类型, 取出字典里面对应的值
        // 21,123,233
        guard let colorArray = colorDict[type.rawValue]  else {return nil}
        
        let array = colorArray as! NSArray
        
        if array.count < 3
        {
            return nil
        }
        
        let red = CGFloat(Int(array[0] as! String)!)
        let green = CGFloat(Int(array[1] as! String)!)
        let blue = CGFloat(Int(array[2] as! String)!)
        
        let color = UIColor(red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha: 1)
    
        return color
        
    }

}
